/**
 * 图片管理
 * @returns {[[Type]]} [[Description]]
 */
define(['../../common/service'],
    function(http) {
        var Manage = function() {};
        Manage.prototype = $.extend(Manage.prototype, {

            init: function() {
                var self = this;
                var p = window.localStorage.getItem('imageEditData');
                if (p) {
                    self.queryImageDefaultInfo(JSON.parse(p));
                }
            },
            /**
             * [bingEvents 绑定事件]
             * @return {[type]} [description]
             */
            bingEvents: function() {
                var self = this;
                var adimagePage = $('.adiamge-row');
                adimagePage.off('click', '.edit-file-name');
                adimagePage.off('focusout', 'input[name="fileName"]');
                $('#btn-save').off('click');

                adimagePage.on('click', '.edit-file-name', $.proxy(self.editFileName, self));
                adimagePage.on('click', '.fa-magic', $.proxy(self.openCountries, self));
                adimagePage.on('focusout', 'input[name="fileName"]', $.proxy(self.modifyFileName, self));
                $('#btn-save').on('click', $.proxy(self.saveAdImages, self));

            },
            /**
             * [queryImageDefaultInfo 显示默认图片标签]
             * @param  {[type]} query [description]
             * @return {[type]}       [description]
             */
            queryImageDefaultInfo: function(params) {
                var self = this;
                if (params) {
                    self.showLoading();
                    http.do('/adresource/showInitTags', {
                        param: JSON.stringify(params)
                    }, 'POST').then(function(result) {
                        self.hideLoading();
                        if (result.flag == 'fail') {
                            kit.alert2(result.msg);
                            return;
                        }
                        result.data.countries = [];
                        $('#adimage-manager-page').remove();
                        $('#image-edit-container').empty();
                        $('#image-edit-container').hide();
                        _.each(result.data.adimgages, function(img, i) {
                            img = self.splitImageName(img);
                            img.createTime = moment(new Date(img.createTime)).format('YYYY/MM/DD HH:mm:ss')
                        });

                        var html = _.template($('#t-adimage-edit').text())(result.data);
                        $('#image-edit-container').html(html).show();
                        self._initTags(result.data);
                        self.bingEvents();

                    }, function(msg, data, type, errorCode) {
                        self.hideLoading();
                        kit.alert2('获取列表失败！');
                    });

                } else {
                    kit.alert2('参数错误!');
                }
            },
            /**
             * [_initTags 初始化tag]
             * @param  {[type]} data [description]
             * @param  {[type]} from [调用来源]
             * @return {[type]}      [description]
             */
            _initTags: function(data, from) {
                var self = this;
                self.initAppTag(data);
                self.initLanguageTag(data);
                self.initSexTag(data);
                self.imgExistArea(data);
            },

            imgExistArea: function(data) {
                $(".img-exist-area").each(function() {
                    var el = $(this),
                        userId = el.data("uploder");
                    if (window.sessionStorage.userId == userId) {
                        el.hide();
                    }
                });
            },

            /**
             * [editFileName 打开编辑文件名称]
             * @param  {[type]} e [description]
             * @return {[type]}   [description]
             */
            editFileName: function(e) {
                var self = this;
                $(e.target).parents('div.file-name-title').toggleClass('hide');
                $(e.target).parents('div.file-name-title').next().toggleClass('hide');
                $(e.target).parents('div.file-name-title').next().focus();
            },
            /**
             * [modifyFileName 关闭修改文件名称]
             * @param  {[type]} e [description]
             * @return {[type]}   [description]
             */
            modifyFileName: function(e) {
                var self = this;
                var imgName = $(e.target).val().trim();
                if (imgName == '' || imgName.length == 0) {
                    imgName = $(e.target).data('orgial-value');
                }
                var imgSuffix = $(e.target).data('suffix');
                $('div.file-name-title').removeClass('hide');
                $('div.file-name-title').next().addClass('hide');
                $(e.target).prev().find('span').html(imgName + imgSuffix);
            },

            /**
             * [valicateQueryParams 验证查询参数]
             * @return {[type]}        [description]
             */
            valicateParams: function() {
                var self = this;
                var isPass = true;
                $('.adiamge-row').each(function(idx, el) {
                    var fileName = $(this).find('input[name="fileName"]');
                    if (fileName.val().length == 0) {
                        fileName.testRemind('请输入文件名');
                        isPass = false;
                    }
                    var appNames = $(this).find('.form-group-select2.app-select2')
                    if (appNames.val() == null || appNames.val().length == 0) {
                        appNames.next().testRemind('请选择应用');
                        appNames.next().focus();
                        isPass = false;
                        return false;
                    }
                    // var countries = $(this).find('.country-select2');
                    // if (countries.select2('val').length == 0) {
                    //     countries.testRemind('请选择国家');
                    //     isPass = false;
                    // }
                });
                return isPass;
            },
            /**
             * [saveAdImages 保存图片数据]
             * @return {[type]} [description]
             */
            saveAdImages: function(e) {
                var self = this;
                if (!self.valicateParams()) {
                    return;
                }
                var adimageArr = [];
                $('.adiamge-row').each(function(idx, el) {
                    var adimage = {};
                    var appNames = $(this).find('.form-group-select2.app-select2').val();
                    var languages = $(this).find('select.language-select2').val();
                    adimage.mongodbId = $(this).data('mid');
                    adimage.fileName = ($(this).find('input[name="fileName"]').val() + $(this).find('input[name="fileName"]').data('suffix'));
                    adimage.appNames = appNames;
                    if (languages) {
                        adimage.languages = languages;
                    } else {
                        adimage.languages = ['']
                    }
                    adimage.gender = $(this).find('select.sex-select2').select2('val');
                    if (adimage.gender.length == 0) {
                        adimage.gender = '0';
                    }
                    //   adimage.interests = $(this).find('input.interest-select2').select2('val');
                    //   adimage.tags = $(this).find('input.other-select2').select2('val');

                    //临时处理：当前操作为审核 插入审核状态参数
                    if (e.target.getAttribute('review') == 'review') {
                        adimage.reviewStatus = 1;
                    }
                    adimageArr.push(adimage);
                });
                var openAdimageModal = $('#open-adimage-modal'),
                    modalAlert = $('.modal-alert', openAdimageModal);



                self.showLoading();
                http.do('/adresource/saveImgTags', {
                    param: JSON.stringify(adimageArr)
                }, 'POST').then(function(result) {
                    self.hideLoading();
                    if (result.flag == 'fail') {
                        kit.alert2(result.msg);
                        return;
                    }
                    modalAlert.html('保存成功').css('color', '#333');
                    //特珠处理：
                    //单独页面 使用在：#!/adimages/edit
                    if (!modalAlert || modalAlert.length == 0) {
                        window.location.hash = '#!imageManage';
                        return;
                    }
                    //弹出框型式 使用在： #!/adimages/manager
                    modalAlert.html('保存成功').css('color', '#333');
                    modalAlert.slideDown(500);
                    window.setTimeout(function() {
                        modalAlert.slideUp();
                        openAdimageModal.modal('hide');
                    }, 1000);


                    //临时处理：当前操作为审核 更改审核状态参数
                    if (e.target.getAttribute('review') == 'review' && data.results && data.results.length > 0) {
                        var _adimageList = $('#adimage-list');
                        $.each(data.results, function(i, v) {
                            $('td[revies-status="' + v.mongodbId + '"]', _adimageList).html('已审核');
                            $('td[revies-reviewer="' + v.mongodbId + '"]', _adimageList).html(v.reviewer);
                            $('.review-action[data-mid="' + v.mongodbId + '"]', _adimageList).parents('td').html('---');
                        });
                    }


                    self.hideLoading();
                }, function(msg, data, type, errorCode) {
                    //特珠处理：
                    //单独页面 使用在：#!/adimages/edit
                    if (!modalAlert || modalAlert.length == 0) {
                        kit.alert2('查询失败,请重试');
                        return;
                    }
                    //弹出框型式 使用在： #!/adimages/manager
                    modalAlert.html('查询失败,请重试').css('color', '#f00');
                    modalAlert.slideDown(500);
                    window.setTimeout(function() {
                        modalAlert.slideUp(500);
                    }, 2000);
                    self.hideLoading();
                    kit.alert2('获取列表失败！');
                });

            },
            /**
             * [openCountries 打开投放控制中的国家]
             * @param  {[type]} e [description]
             * @return {[type]}   [description]
             */
            openCountries: function(e) {
                var self = this;
                var from = '';
                $('.popover.fade.bottom.in').remove(); //只保留一个
                var appIds = $(e.target).parents('.adiamge-row').find('input.form-group-select2.app-select2').select2('val').join('|');
                var countrySelect2 = $(e.target).parents('.adiamge-row').find('input.form-group-select2.country-select2');
                var appSelect = countrySelect2;
                var par = {
                    fbConnectionObjectIds: appIds
                }


                self.showLoading();
                http.do('/adresource/getAppcountries', {
                    param: JSON.stringify(params)
                }, 'POST').then(function(result) {
                    self.hideLoading();
                    if (result.flag == 'fail') {
                        kit.alert2(result.msg);
                        return;
                    }

                    if (appCountries.length == 0) {
                        common.msgs.pop_up('没有可选的国家', 'info');
                    } else {
                        var popover = $(e.target).parent();
                        popover.popover('destroy');
                        var selectedData = appSelect.select2('data');
                        _.each(appCountries, function(v) {
                            v.countries = _.sortBy(v.countries, function(item) {
                                return (item.name) ? item.name.toLowerCase() : item.toLowerCase();
                            });
                            var checkedNum = 0;
                            for (var i = 0; i < v.countries.length; i++) {
                                var c = v.countries[i];
                                if (c.checked) {
                                    c.checked = '';
                                } else {
                                    var ctr = {
                                        checked: '',
                                        name: c
                                    }
                                    v.countries[i] = ctr;
                                    c = ctr;
                                }
                                for (var j = 0; j < selectedData.length; j++) {
                                    var s = selectedData[j];
                                    if (c.name == s.id) {
                                        c.checked = 'checked';
                                        checkedNum++;
                                        break;
                                    }
                                };
                            };
                            if (checkedNum == v.countries.length) {
                                v.checked = 'checked'
                            }
                        });
                        var d = {
                            appCountries: appCountries
                        }
                        var html = common._t('t-edit-image-counties-content', d);
                        if ($('#popover-from').data('from') == 'model') {
                            popover.popover({
                                content: html
                            });
                        } else {
                            popover.popover({
                                content: html,
                                container: 'body'
                            });
                        }
                        popover.popover('show');

                        $('.popover.fade.bottom.in .close').on('click', function(e) {
                            popover.popover('destroy');
                        });
                        // 单选
                        $('.popover .smart-form input[name=checkbox-inline]').on('click', function(e) {
                            var checkedLength = $(e.target).parent().parent().find('input[name=checkbox-inline]:checked').length;
                            var allCheckedLength = $(e.target).parent().parent().find('input[name=checkbox-inline]').length;
                            $(e.target).parent().parent().prev().find('input[name=checkbox-all]').prop('checked', (checkedLength == allCheckedLength));
                            self._setOpenCountries(appSelect, e);
                        });
                        //全选
                        $('.popover .smart-form input[name=checkbox-all]').on('click', function(e) {
                            $(e.target).parent().parent().find('input[name=checkbox-inline]').prop("checked", $(e.target).prop('checked'));
                            self._setOpenCountries(appSelect, e);
                        });
                    }


                    self.hideLoading();
                }, function(msg, data, type, errorCode) {
                    self.hideLoading();
                    kit.alert2('获取列表失败！');
                });



            },

            /**
             * [_setOpenCountries 设置国家选择]
             * @param {[type]} appSelect [description]
             * @param {[type]} e         [description]
             */
            _setOpenCountries: function(appSelect, e) {
                var checkedCountries = [];
                var unCheckedCountries = [];
                $('.popover .smart-form input[name=checkbox-inline]').each(function(idx, el) {
                    var val = $(this).val();
                    var c = {
                        id: val,
                        text: val
                    }
                    if ($(this).prop('checked')) {
                        checkedCountries.push(c);
                    } else {
                        unCheckedCountries.push(c);
                    }
                });
                var selectedCtr = appSelect.select2('data');
                var alldata = _.union(selectedCtr, checkedCountries);
                var filterData = [];
                for (var i = 0; i < alldata.length; i++) {
                    var a = alldata[i];
                    var result = true;
                    for (var j = 0; j < unCheckedCountries.length; j++) {
                        var c = unCheckedCountries[j]
                        if (a.text == c.text) {
                            result = false;
                            break;
                        }
                    };
                    if (result) {
                        filterData.push(a);
                    }
                };
                appSelect.select2('data', filterData)
            },
            /**
             * [initAppTag 初始化应用标签]
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            initAppTag: function(data) {
                var self = this;
                var params = {
                    typeId: 2
                };
                http.do('/connectionobjects/searchConnectionObjectsByResourceManage', {
                    param: JSON.stringify(params)
                }, 'POST').then(function(result) {
                    self.hideLoading();
                    if (result.flag == 'fail') {
                        kit.alert2(result.msg);
                        return;
                    }
                    var app = result.data;
                    var opts = [];
                    if (app && app.length > 0) {
                        app = _.sortBy(app, function(item) {
                            return item.name.toLowerCase();
                        });

                        $('select.form-group-select2.app-select2').each(function(index, el) {
                            $(this).empty();
                            var adimage = data.adimgages[index];
                            adimage.appNames.push(data.appNames[0]);
                            var options = '';
                            $.each(app, function(index, v) {
                                var selected = false;
                                $.each(adimage.appNames, function(j, o) {
                                    if (v.name == o) {
                                        selected = true;
                                        return false;
                                    }
                                });
                                options = options + '<option value="' + v.name + '" ' + (selected ? 'selected="selected"' : '') + '>' + v.name + '</option>';
                            })
                            $(this).html(options);
                            $(this).select2();
                        });
                    }
                    self.hideLoading();
                }, function(msg, data, type, errorCode) {
                    self.hideLoading();
                    kit.alert2('获取列表失败！');
                });


            },
            /**
             * 遍历 apps 找到appName值
             * @param appName
             * @param apps
             */
            findApp: function(appName, apps) {
                var obj;
                $.each(apps, function(idx, v) {
                    if (v.name == appName) {
                        obj = v;
                    }
                });
                return obj;
            },
            /**
             * [initCountryTag 初始化国家标签]
             * @param  {[type]} data [description]
             * @param  {[type]} from [调用来源]
             * @return {[type]}      [description]
             */
            initCountryTag: function(data, from) {
                console.log('已废弃');
                var self = this;
                var params = {
                    "locale": I18N.language,
                    "cType": "country"
                };
                var appSelect = $('input.form-group-select2.country-select2');
                var url = ['search', 'searchAdgeolocation'];
                var sortName = 'name';
                var idName = 'name';
                var initTagName = 'countries';
                self._initCountryTagFlag = true;
                self._initSearchTag(data, appSelect, params, url, sortName, idName, idName, initTagName);

            },

            /**
             * [initLanguageTag 初始化语言标签]
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            initLanguageTag: function(data) {
                var self = this;
                var params = {
                    "type": "adlocale",
                    "locale": I18N.language,
                    "q": ""
                };
                var appSelect = $('select.form-group-select2.language-select2');
                var url = ['search', 'searchAdlocale'];
                var sortName = 'name';
                var idName = 'name';
                var initTagName = 'languages';
                // self._initSearchTag(data, appSelect, params, url, sortName, idName, idName, initTagName);


                http.do('/search/searchAdlocale', {
                    param: JSON.stringify(params)
                }, 'POST').then(function(result) {
                    self.hideLoading();
                    if (result.flag == 'fail') {
                        kit.alert2(result.msg);
                        return;
                    }
                    var languages = result.data;
                    var opts = [];
                    if (languages && languages.length > 0) {
                        languages = _.sortBy(languages, function(item) {
                            return item.name.toLowerCase();
                        });

                        $('select.form-group-select2.language-select2').each(function(index, el) {
                            $(this).empty();
                            var adimage = data.adimgages[index];
                            var options = '';
                            $.each(languages, function(index, v) {
                                var selected = false;
                                if (adimage.languages) {
                                    $.each(adimage.languages, function(j, o) {
                                        if (v.name == o) {
                                            selected = true;
                                            return false;
                                        }
                                    });
                                }
                                options = options + '<option value="' + v.name + '" ' + (selected ? 'selected="selected"' : '') + '>' + v.name + '</option>';
                            })
                            $(this).html(options);
                            $(this).select2();
                        });
                    }
                    self.hideLoading();
                }, function(msg, data, type, errorCode) {
                    self.hideLoading();
                    kit.alert2('获取列表失败！');
                });







            },
            /**
             * [initSexTag 初始化性别标签]
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            initSexTag: function(data) {
                var self = this;
                var appSelect = $('select.form-group-select2.sex-select2');

                appSelect.each(function(idx, v) {
                    var imgAppSelct = $(this);
                    var dataMid = imgAppSelct.attr("data-mid");

                    // 找到对应的img
                    var imgs = data.adimgages,
                        gender = '';
                    $.each(imgs, function(idx, v) {
                        if (v.mongodbId == dataMid) {
                            var initTag = v['gender'];
                            if (initTag) {
                                gender = initTag[0];
                            }
                        }
                    });

                    imgAppSelct.find("option[value='" + gender + "']").attr("selected", true);
                    imgAppSelct.select2({
                        minimumResultsForSearch: Infinity
                    });
                });

            },
            /**
             * [initInterstTag 初始化风格标签]
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            initInterstTag: function(data) {
                var self = this;
                var params = {
                    "type": "adinterest",
                    "locale": "en_US"
                };
                var appSelect = $('input.form-group-select2.interest-select2');
                var url = ['search', 'searchInterests'];
                var sortName = 'name';
                var idName = 'name';
                var initTagName = 'interests';

                self._initSearchTag(data, appSelect, params, url, sortName, idName, idName, initTagName);
            },
            initOtherTag: function(data) {
                var self = this;
                var appSelect = $('input.form-group-select2.other-select2');
                appSelect.select2({
                    placeholder: '请输入文本',
                    tags: [],
                    tokenSeparators: [',', ' ']
                });
                var datas = [];
                if (data.tags && data.tags.length > 0) {
                    _.each(data.tags, function(el) {
                        var c = {
                            id: el,
                            text: el
                        }
                        datas.push(c);
                    });
                }
                appSelect.select2('data', datas)
                appSelect.on("select2-open", function(e) {
                    $('.select2-drop-active .select2-no-results').html('请输入自定义标签');
                });
            },
            /**
             * [_initSearchTag 简化searchtag 的接口,避免大量重复代码]
             * @param  {[type]}   data     [description]
             * @param  {[type]}   $dom     [description]
             * @param  {[type]}   params   [description]
             * @param  {[type]}   url      [是个数组,例如 ['connectionobjects', 'searchAppsAndConfigurations'] ]
             * @param  {[type]}   sortName   [排序字段名称]
             * @param  {[type]}   idName   [初始化备选值的字段名称]
             * @param  {[type]}   idText   [初始化备选值的字段名称]
             * @param  {[type]}   initTagName   [初始化tag值的字段名称]
             * @param  {Function} callback [description]
             * @return {[type]}            [description]
             */
            _initSearchTag: function(data, $dom, params, url, sortName, idName, idText, initTagName, callback) {
                var self = this;
                var tagSelect = $dom;
                tagSelect.select2();

                self.showLoading();
                http.do('/' + url[0] + '/' + url[1] + '', {
                    param: JSON.stringify(params)
                }, 'POST').then(function(result) {
                    self.hideLoading();
                    if (result.flag == 'fail') {
                        kit.alert2(result.msg);
                        return;
                    }
                    var opts = [];
                    result.data = _.sortBy(result.data, function(item) {
                        if (item[sortName] && item[sortName].length > 0) {
                            return item[sortName].toLowerCase();
                        } else {
                            0;
                        }
                    });
                    $.each(result.data, function(index, v) {
                        opts.push({
                            id: v[idName],
                            text: v[idText]
                        })
                    })
                    tagSelect.select2('data', opts);




                    tagSelect.each(function(idx, v) {
                        var imgAppSelct = $(this);
                        var dataMid = imgAppSelct.attr("data-mid");
                        // 找到对应的img
                        var imgs = data.adimgages;
                        var datas = [];
                        $.each(imgs, function(idx, v) {
                            if (v.mongodbId == dataMid) {
                                var initTag = v[initTagName];
                                if (initTag) {
                                    $.each(initTag, function(x, vv) {
                                        datas.push({
                                            id: vv,
                                            text: vv
                                        });
                                    });
                                }
                            }
                        });
                        imgAppSelct.select2('data', datas)
                    });


                    self.hideLoading();
                }, function(msg, data, type, errorCode) {
                    self.hideLoading();
                    kit.alert2('获取列表失败！');
                });




                if (callback) {
                    callback(tagSelect);
                }
            },
            /**
             * [splitImageName 分割图片名称]
             * @param  {[type]} img [description]
             * @return {[type]}           [description]
             */
            splitImageName: function(img) {
                if (img.name && img.name.length > 0 && (img.name.lastIndexOf('.') > -1)) {
                    var idx = img.name.lastIndexOf('.')
                    img.imgSuffix = img.name.substr(idx);
                    img.imgName = img.name.substr(0, idx);
                } else {
                    img.imgName = img.name;
                    img.imgSuffix = '';
                }
                return img;
            },
            showLoading: function() {
                var self = this;
                var loadingArea = $('#adimage-edit-page');
                kit.loading.show(loadingArea);
            },
            hideLoading: function() {
                var self = this;
                var loadingArea = $('#adimage-edit-page');
                kit.loading.hide(loadingArea);
            },
            dispose: function() {

            }

        });
        return new Manage();

    });
